import React, { ReactNode } from "react";
import User from "./User";
import { addBlockedUser, existBlockUser, removeBlockUser, USER_LIST_KEY } from "./utils";
interface IProps { user: User, isBlocked: boolean }

interface IState { user: User, isBlocked: boolean }

export default class BlockButtonComponent extends React.Component<IProps, IState> {
    constructor(props: IProps) {
        super(props);
        this.state = {
            user: props.user,
            isBlocked: props.isBlocked
        };
    }

    componentDidMount() {
        // 监听屏蔽列表的改变
        chrome.storage.onChanged.addListener(async (changes, namespace) => {
            for (let [key, { oldValue, newValue }] of Object.entries(changes)) {
                if (key == USER_LIST_KEY) {
                    // 判断当前user是否在block list中
                    let isBlocked = await existBlockUser(this.state.user.id);
                    console.log(`BlockButtonComponent isBlocked ${isBlocked}`);
                    this.setState({ isBlocked: isBlocked });
                }
            }
        });
    }

    // 渲染按钮
    public render(): ReactNode {
        return (
            <button
                // disabled={this.state.isBlocked}
                type="button"
                onClick={async () => { await this.handleClick(); }}
                style={{
                    background: this.state.isBlocked ? "gray" : "red",
                    color: "white"
                }}
            >{this.state.isBlocked ? "取消标红" : "标红"}</button>
        )
    }

    // 处理按钮点击事件
    async handleClick() {
        // 如果已经屏蔽了,执行反屏蔽操作
        if (this.state.isBlocked) {
            await removeBlockUser(this.state.user.id);
            // 更改state
            this.setState({
                isBlocked: false
            });
        }
        // 如果还没有屏蔽,执行屏蔽操作
        else {
            // 添加到Blocked名单
            await addBlockedUser(this.state.user);
            // 更改state
            this.setState({
                isBlocked: true
            });
        }
    }
}